package Dao.Impl;

import Dao.TransactionDAO;
import Model.Transaction;
import Util.DbConnector;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class TransactionDAOImpl implements TransactionDAO {
    private static final Logger logger = LogManager.getLogger(TransactionDAOImpl.class);
    private final QueryRunner queryRunner = new QueryRunner();

    public TransactionDAOImpl() {
    }

    @Override
    public void addTransaction(Transaction transaction) {
        String sql = "INSERT INTO transactions(userId, recipientId, transactionType, amount, totalBalance, description) VALUES(?, NULL, ?, ?, ?, ?)";
        try (Connection connection = DbConnector.getConnection()) {
            int affectedRows = queryRunner.update(connection, sql,
                    transaction.getUserId(),
                    transaction.getTransactionType(),
                    transaction.getAmount(),
                    transaction.getTotalBalance(),
                    transaction.getDescription()
            );

            if (affectedRows == 0) {
                throw new SQLException("创建交易失败，没有行受到影响。");
            }
            logger.info("添加交易成功，交易ID: {}", transaction.getId());
        } catch (SQLException e) {
            logger.error("添加交易失败，交易ID: {}", transaction.getId(), e);
        }
    }

    @Override
    public List<Transaction> getTransactionsByUserId(int userId) {
        String sql = "SELECT * FROM Transactions WHERE userId = ? ORDER BY id DESC";
        try (Connection connection = DbConnector.getConnection()) {
            return queryRunner.query(connection, sql, new BeanListHandler<>(Transaction.class), userId);
        } catch (SQLException e) {
            logger.error("获取用户交易失败，用户ID: {}", userId, e);
            return null;
        }
    }
}